<template>
  <div class="choosePresent">
    <x-header class="header" :left-options="{showBack: showHeaderBack}" ref="header">选择要赠送商品</x-header>
    <div class="topHolder"></div>
    <scroll-menu :headerHeight="headerHeight" :items="goodItemsList"
                 :selectItems="selectItems" :imgPath="contextPath"
                 @add-number="addNumber" @minus-number="minusNumber"
                 @to-pay="toPay" @clear-selected="clearSelected"
                 @clear-choosen-multi-spec="clearChoosenMultiSpec" @change-multi-spec="changeMultiSpec"></scroll-menu>
  </div>
</template>

<script>
  import { numberComma } from 'vux'
  import ScrollMenu from '../../components/scrollMenu'
  import {getChoosePresentList,checkStock,contextPath} from "../../api";
  import {message,toDecimal2,Trim} from "../../common/util";

  export default {
    name:'choosePresent',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        paramOrderId:this.$route.params.orderId,
        paramType:this.$route.params.type,
        loadingStatus:true,
        contextPath:contextPath,
        headerHeight:0,
        goodItemsList: [],
        selectItems:[],
        choosenMatchingDrinkId:'',
        choosenMealSetItemIds:[]
      }
    },
    components:{
      ScrollMenu
    },
    computed:{
      salesPresentList:{
        get () {
          return this.$store.getters.getSalesPresentList
        },
        set (value) {
          this.$store.commit('updateSalesPresentList', value)
        }
      },
      salesMaxNumber:{
        get () {
          return this.$store.getters.getSalesMaxNumber
        },
        set (value) {
          this.$store.commit('updateSalesMaxNumber', value)
        }
      },
      keepPresentList:{
        get () {
          return this.$store.getters.getKeepPresentList
        },
        set (value) {
          this.$store.commit('updateKeepPresentList', value)
        }
      },
      girlPresentList:{
        get () {
          return this.$store.getters.getGirlPresentList
        },
        set (value) {
          this.$store.commit('updateGirlPresentList', value)
        }
      },
      salesSelectedList:{
        get () {
          return this.$store.getters.getSalesSelectedList
        },
        set (value) {
          this.$store.commit('updateSalesSelectedList', value)
        }
      },
      keepSelectedList:{
        get () {
          return this.$store.getters.getKeepSelectedList
        },
        set (value) {
          this.$store.commit('updateKeepSelectedList', value)
        }
      },
      girlSelectedList:{
        get () {
          return this.$store.getters.getGirlSelectedList
        },
        set (value) {
          this.$store.commit('updateGirlSelectedList', value)
        }
      },
      selectItemTotal(){
        let total = 0
        for(let item of this.selectItems){
          total = total + 1*item.QUANTITY
        }
        return total
      }
    },
    methods:{
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      changeMultiSpec(choosen){
        this.choosenMatchingDrinkId = choosen.choosenMatchingDrinkId
        this.choosenMealSetItemIds = choosen.choosenMealSetItemIds
      },
      clearChoosenMultiSpec(){
        this.choosenMatchingDrinkId = ''
        this.choosenMealSetItemIds = []
      },
      addNumber(item){
        if(this.paramType == 'salePresent' && this.salesMaxNumber <= this.selectItemTotal) {
          message({message:'已达到本周期内可赠送最大商品数量',type:'info'})
          return
        }
        let tempCMD = '',tempCMST = '',choosenMatchingDrink = '',choosenMealSetItems = []
        if(item.MATCHINGDRINK != undefined && item.MATCHINGDRINK.replace(/\s+/g,'') != ''){//获取选中的配饮对象
          for(let mDItem of JSON.parse(item.MATCHINGDRINK)){
            if(mDItem.MATCHINGDRINK_ID == this.choosenMatchingDrinkId){
              choosenMatchingDrink = mDItem
            }
          }
        }
        if(item.GOODS_LIST && item.GOODS_LIST.length > 0){//获取选中的套餐商品对象列表
          for(let mSItem of item.GOODS_LIST){
            for(let cMSIId of this.choosenMealSetItemIds){
              if(mSItem.GOODS_ID == cMSIId){
                choosenMealSetItems.push(mSItem)
              }
            }
          }
        }
        //判断是否为非首次添加的商品，非首次已有choosenMatchingDrink参数
        if(item.choosenMatchingDrink != '' && item.choosenMatchingDrink != undefined) tempCMD = item.choosenMatchingDrink
        else tempCMD = this.choosenMatchingDrinkId != ''?choosenMatchingDrink:''
        //判断是否为非首次添加的商品，非首次已有choosenMealSetItems参数
        if(item.choosenMealSetItems != undefined && item.choosenMealSetItems.length > 0) tempCMST = item.choosenMealSetItems
        else tempCMST = choosenMealSetItems.length > 0?choosenMealSetItems:[]
        //中转变量
        let tempItem = JSON.parse(JSON.stringify(item))
        tempItem.GOODS_LIST = tempItem.GOODS_LIST?tempItem.GOODS_LIST:''
        tempItem.MATCHINGDRINK = tempItem.MATCHINGDRINK?tempItem.MATCHINGDRINK:''
        tempItem.choosenMatchingDrink = tempCMD
        tempItem.choosenMealSetItems = tempCMST
        let flag = true
        this.selectItems.some((orderedItem) => {
          if(orderedItem.GOODS_ID == tempItem.GOODS_ID //检查商品的ID是否对得上
            && orderedItem.choosenMatchingDrink.MATCHINGDRINK_ID == tempItem.choosenMatchingDrink.MATCHINGDRINK_ID//检查选中的配饮是否对得上
            && this.checkMealSetItems(orderedItem.choosenMealSetItems,tempItem.choosenMealSetItems)//检查选中的套餐商品是否对得上
          ){
            orderedItem.QUANTITY++
            orderedItem.amount = this.formatCurrency(orderedItem.QUANTITY*orderedItem.PRICE)
            flag = false
            return true
          }
        })
        if(flag){//不在已点列表上，直接新添加一项
          for(let typeItem of this.goodItemsList){
            typeItem.list.some(item =>{
              if(item.GOODS_ID == tempItem.GOODS_ID){
                tempItem.QUANTITY = 1
                tempItem.amount = this.formatCurrency(tempItem.QUANTITY*tempItem.PRICE)
                this.selectItems.push(tempItem)
                return true
              }
            })
          }
        }
      },
      minusNumber(item){
        this.selectItems.some((orderedItem, orderedIndex) => {
          let judge = ''
          if((item.MATCHINGDRINK == undefined || Trim(item.MATCHINGDRINK,'g') == '') && (!item.GOODS_LIST || item.GOODS_LIST.length <= 0))
            judge = item.GOODS_ID == orderedItem.GOODS_ID //检查商品的ID是否对得上
          else
            judge = item.GOODS_ID == orderedItem.GOODS_ID //检查商品的ID是否对得上
              && item.choosenMatchingDrink.MATCHINGDRINK_ID == orderedItem.choosenMatchingDrink.MATCHINGDRINK_ID//检查选中的配饮是否对得上
              && this.checkMealSetItems(orderedItem.choosenMealSetItems,item.choosenMealSetItems)//检查选中的套餐商品是否对得上
          if(judge){
            orderedItem.QUANTITY--
            orderedItem.amount = this.formatCurrency(orderedItem.QUANTITY*orderedItem.PRICE)
            if(orderedItem.QUANTITY <= 0){
              this.selectItems.splice(orderedIndex,1)
            }
            return true
          }
        })
      },
      checkMealSetItems(ordered,choosen){//检查套餐选中内容与已选内容是否完全匹配
        let flag = 0
        for(let orderedItem of ordered){
          for(let choosenItem of choosen){
            if(orderedItem.GOODS_ID == choosenItem.GOODS_ID){
              flag++
              break
            }
          }
        }
        if(flag == choosen.length) return true
        else return false
      },
      toPay(){
        if(this.selectItems.length <= 0)message({message:'请先选择赠品',type:'info'})
        else{
          let reqParams = {
            selectedList:this.selectItems,
            type:this.paramType
          }
          checkStock(reqParams).then((res)=>{
            if(res.status == 'success'){
              if(res.data) this.$router.push({name:'提交赠送',params:{type:this.paramType,orderId:this.paramOrderId}})
              else message({message:res.msg + '商品库存不足，请重新选择',type:'error'})
            }else if(res.status == 'error'){
              message({message:res.msg,type:'error'})
              console.log('checkStock error info:', res.msg)
            }
          }).catch((err)=>{console.log('checkStock catch info:',err)})
        }
      },
      clearSelected(){
        this.loadingStatus = true
        this.$vux.confirm.show({
          title:'确认清空',
          content:'是否清空所选商品？',
          onCancel: ()=> {
            this.loadingStatus = false
          },
          onConfirm: ()=> {
            this.selectItems = []
            switch (this.paramType) {
              case 'salePresent':this.salesSelectedList = [];break
              case 'keepPresent':this.keepSelectedList = [];break
              case 'girlPresent':this.girlSelectedList = [];break
              default:break
            }
          }
        })
      }
    },
    mounted(){
      this.headerHeight = this.$refs.header.$el.offsetHeight
      return new Promise((resolve, reject) => {
        if((this.paramType == 'salePresent' && this.salesPresentList.length <= 0) ||
          (this.paramType == 'keepPresent' && this.keepPresentList.length <= 0) ||
          (this.paramType == 'girlPresent' && this.girlPresentList.length <= 0))
          getChoosePresentList(this.paramType).then((res)=>{
            if(res.status == 'success'){
              switch (this.paramType) {
                case 'salePresent':this.salesPresentList = res.data.list;this.salesMaxNumber = res.data.maxNumber;break
                case 'keepPresent':this.keepPresentList = res.data.list;break
                case 'girlPresent':this.girlPresentList = res.data.list;break
                default:break
              }
              resolve()
            }else if(res.status == 'error') {
              message({message:res.msg,type:'error'})
              console.log('getChoosePresentList error info:', res.msg)
            }
          }).catch((err)=>{console.log('getChoosePresentList catch info:',err)})
        else resolve()
      }).then(()=>{
        switch (this.paramType) {
          case 'salePresent':
            this.goodItemsList = this.salesPresentList
            this.selectItems = this.salesSelectedList
            break
          case 'keepPresent':
            this.goodItemsList = this.keepPresentList
            this.selectItems = this.keepSelectedList
            break
          case 'girlPresent':
            this.goodItemsList = this.girlPresentList
            this.selectItems = this.girlSelectedList
            break
          default:break
        }
        this.loadingStatus = false
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    }
  }
</script>

<style lang="scss" scoped>
  .choosePresent{

  }
</style>
